import request from '@/utils/request'

// 根据userId查询家长信息
export function getParentProfileByUserId(userId) {
  return new Promise((resolve, reject) => {
    request({
      url: `/parentProfile/parentProfile/byUserId/${userId}`,
      method: 'get'
    }).then(response => {
      if (response.code === 200 && response.data) {
        resolve(response.data);
      } else {
        // 如果家长信息不存在，返回空对象而不是抛出错误
        resolve({});
      }
    }).catch(err => {
      // 发生错误时也返回空对象
      resolve({});
    });
  });
}

// 通过user_id获取家长联系方式
export function getParentPhone(userId) {
  return request({
    url: "/parentProfile/parentProfile/getParentPhone/" + userId,
    method: "get",
  });
}

// 查询家长信息列表
export function listParentProfile(query) {
  return request({
    url: '/parentProfile/parentProfile/list',
    method: 'get',
    params: query
  })
}

// 查询家长信息详细
export function getParentProfile(parentId) {
  return request({
    url: '/parentProfile/parentProfile/' + parentId,
    method: 'get'
  })
}

// 新增家长信息
export function addParentProfile(data) {
  // 确保传递userId
  const parentData = {
    ...data,
    userId: data.userId || localStorage.getItem("userId")
  };
  return request({
    url: '/parentProfile/parentProfile',
    method: 'post',
    data: parentData
  })
}

// 修改家长信息
export function updateParentProfile(data) {
  return new Promise((resolve, reject) => {
    const parentData = {
      ...data,
      userId: data.userId || localStorage.getItem("userId")
    };
    listParentProfile({ userName: parentData.userName }).then(response => {
      if (response.rows && response.rows.length > 0) {
        const parentId = response.rows[0].parentId;
        // 将parentId加入请求体
        parentData.parentId = parentId; // 确保parentId在请求体中
        request({
    url: '/parentProfile/parentProfile',
    method: 'put',
          data: parentData // 请求体包含parentId
        }).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      } else {
        reject(new Error('未找到对应的家长信息'));
      }
    }).catch(err => {
      reject(err);
    });
  });
}

// 删除家长信息
export function delParentProfile(parentId) {
  return request({
    url: '/parentProfile/parentProfile/' + parentId,
    method: 'delete'
  })
}
